<?php
/**
 * Клас базовой модели c_base_model
 *
 * @author tonatos
 */
class c_base_model {

    public function __construct($data=null) {
        global $modx;

        $this->m_table = substr(get_class($this),2,-6);
        if (is_object($data)||(is_array($data))){
            foreach ($data as $key=>$value){
                $this->$key = $value;
            }
        }

        if (is_numeric($data)){
            $this->id = $data;
            $this->load();
        }

        return $this;
    }

    public function load(){
        global $modx;
        $data = $modx->db->get_record($this->m_table,"id=".(int)$this->id);
        if ($data===false){
            throw new Exception('Объект не найден '. $this->m_table." id = $this->id");
            return false;
        }
        foreach ($data as $key=>$value){
            $this->$key = $value;
        }

        $this->after_load();
        return true;
    }

    public function delete(){
        global $modx;
        return $modx->db->delete($modx->getFullTableName($this->m_table),"id=".(int)$this->id);
    }

    public function after_load(){}

    public function before_insert(){}
    
    public function before_update(){}

    public function after_insert(){}
    
    public function after_update(){}

    public function prepare_data(){
        global $modx;
        $data = array();

        foreach($this  as $key=>$value){

            //Пропускаем локальные переменные
            if (substr($key,0,2)=="m_") continue;

            //Пропускаем объекты
            if (is_object($value)) continue;
            
            $data[$key] = "'".$modx->db->escape($value)."'";
        }
        return $data;
    }


    public function save(){
        global $modx;
        if (!empty($this->id)){
            $this->before_update();
            $data = $this->prepare_data();
            $sql=array();
            foreach($data as $key=>$value){
                $sql[] = "$key = $value ";
            }
            $sql="update ".$modx->getFullTableName($this->m_table)." set ".implode(",",$sql)." where id = $this->id";
            $modx->db->query($sql);
	    $this->after_update();
        }else{
            $this->before_insert();
            $data = $this->prepare_data();

            $keys = array_keys($data);
            $values = array_values($data);

            $sql="insert into ".$modx->getFullTableName($this->m_table)." (".implode(",",$keys).") values (".implode(",",$values).")";
            $modx->db->query($sql);
            $this->id = $modx->db->getInsertId();
	    $this->after_insert();
        }
    }

    public static function find_all($sort = "id desc"){
        global $modx;
        return $modx->db->get_records($this->m_table,"",$modx->db->escape($sort));
    }

}
?>
